<template>
  <a-spin :spinning="confirmLoading">
    <KFormBuild :disabled="disabled" class="k-form-design" ref="kdf" :nodeId="task.taskDefinitionKey" :task="task" :value="formModel" />
  </a-spin>
</template>

<script>
import { KFormBuild } from '@/components/k-form-design/packages/use.js'
import { getAction } from '@/services/manage'
import { getSelectDictCode, getSelectOptions } from '@/utils/k-form-design'

export default {
  name: 'TaskForm',
  components: {
    KFormBuild
  },
  props: {
    task: {
      type: Object,
      default: () => {}
    },
    formData: {
      type: Object,
      default: () => {}
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      url: {
        taskForm: '/camunda/task/form/model/'
        // taskForm: '/camunda/process/details/'
      },
      formModel: {},
      dynamicDataSatrt: {},
      confirmLoading: false
    }
  },
  watch: {
    formData: {
      handler() {
        if (Object.keys(this.formData).length > 0) {
          this.$nextTick(() => {
            this.$refs.kdf.setData(this.formData)
          })
        }
      },
      deep: true,
      immediate: true
    },
    'task.id': {
      handler(val) {
        if (val) {
          this.getTaskForm()
        }
      },
      immediate: true
    }
  },
  methods: {
    async getTaskForm() {
      const res = await getAction(this.url.taskForm + this.task.id)
      if (!res.success) {
        this.confirmLoading = false
        return this.$message.warning('未查询到发起表单')
      }
      const formModel = res.result && res.result.model && JSON.parse(res.result.model)

      // 调整为后台接口直接返回节点是否包含表单
      // if (!formModel) {
      //   this.$emit('init', false)
      //   return
      // }
      // this.$emit('init', true)

      // 在渲染前获取到dynamicData --start
      let dictCodes = getSelectDictCode(formModel.list)
      dictCodes = Array.from(new Set(dictCodes))
      this.dynamicDataSatrt = await getSelectOptions(dictCodes)
      // -- end

      this.formModel = formModel
      // setTimeout(() => {
      //   this.$refs.kdf.setData(this.formData)
      // }, 1000)
    },
    async getData() {
      return this.$refs.kdf.getData()
    }
  }
}
</script>

<style>

</style>
